package cn.otrue.patienthealthmanager.fragment;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import android.app.AlertDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.Fragment;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import cn.otrue.patienthealthmanager.R;
import cn.otrue.patienthealthmanager.activity.LoginActivity;
import cn.otrue.patienthealthmanager.adapter.TextAdapter;
import cn.otrue.patienthealthmanager.bean.TransferParameter;
import cn.otrue.patienthealthmanager.http.HttpCons;
import cn.otrue.patienthealthmanager.http.HttpServer;
import cn.otrue.patienthealthmanager.http.ServerHandler;
import cn.otrue.patienthealthmanager.utils.CommonUtil;
import cn.otrue.patienthealthmanager.utils.DateFormatUtils;
import cn.otrue.patienthealthmanager.utils.DialogUtil;
import cn.otrue.patienthealthmanager.utils.JsonParser;
import cn.otrue.patienthealthmanager.utils.MyConst;
import cn.otrue.patienthealthmanager.utils.NumberUtils;
import cn.otrue.patienthealthmanager.utils.OnCallBackListener;
import cn.otrue.patienthealthmanager.view.AscertainPopupWindow;
import cn.otrue.patienthealthmanager.view.GetPickResultListener;
import cn.otrue.patienthealthmanager.view.MyGridView;
import cn.otrue.patienthealthmanager.view.MyPopupWindow;

import com.google.gson.reflect.TypeToken;
import com.iflytek.cloud.RecognizerListener;
import com.iflytek.cloud.RecognizerResult;
import com.iflytek.cloud.SpeechConstant;
import com.iflytek.cloud.SpeechError;
import com.iflytek.cloud.SpeechRecognizer;
import com.iflytek.cloud.SpeechUtility;

/**
 * 首页->数据采集
 * 
 * @author G
 * 
 */
public class MainDataPickFragment extends BaseFragment implements
		OnTouchListener, OnItemClickListener {

	private RelativeLayout ll_catt_pressure_advise_pickTime;
	private TextView tv_catt_pressure_pickTime;
	private TextView tv_catt_pressure_advise;
	private RelativeLayout ll_catt_plus_advise_pickTime;
	private TextView tv_catt_plus_pickTime;
	private TextView tv_catt_plus_advise;
	public final static int ADDTYPE_SUGAR_BEFOREMEAL = 31;
	public final static int ADDTYPE_SUGAR_AFTERMEAL = 32;
	public final static int ADDTYPE_SUGAR = 315;
	public final static int ADDTYPE_PLUS = 33;
	public final static int ADDTYPE_PRESSURE_HIGH = 34;
	public final static int ADDTYPE_PRESSURE_LOW = 35;
	public final static int ADDTYPE_BODY_STATE = 36;

	private float beforeMealSugar = 0;
	private float afterMealSugar = 0;
	private int highPressure = 0;
	private int lowPressure = 0;
	private int plus = 0;
	private String comment_sugar = "";
	private String comment_pressure = "";
	private String comment_plus = "";
	private String plus_pickTime = "";
	private String sugar_pickTime = "";
	private String pressure_pickTime = "";

	/** 对话框弹出时的参照物 */
	private View mainView;
	/** 选择日期的按键 */
	private TextView tv_data_pick_pickdate;

	/** 是否存在配置参数 */
	private boolean isPickSettingFound;

	private View rootView;
	/** 数据采集时用户输入的数据 */
	private EditText et_catt_data;
	/** 饭前血糖显示 */
	private TextView tv_catt_data_bloodSugar1;
	/** 饭后血糖显示 */
	private TextView tv_catt_data_bloodSugar2;
	/** 心率显示 */
	private TextView tv_catt_data_heartPlus;
	/** 血压高压显示 */
	private TextView tv_catt_data_pressture1;
	/** 血压低压显示 */
	private TextView tv_catt_data_pressture2;
	private RelativeLayout ll_catt_booldSugar_advise_pickTime;
	private TextView tv_catt_booldSugar_pickTime;
	private TextView tv_catt_booldSugar_advise;
	/** 当前用户选择的日期 */
	private String selectedDate = "";
	/** 控制各个容器显示与否的开关 */

	private int sugar_bg, pressure_bg, puls_bg;
	private int plus_data_bg, pressure_data_bg, sugar_data_bg;
	private int alert_data_bg;

	private AlertDialog alertDialog;
	private MyGridView gv_catt_other;

	public String bodyState_pickTime;
	private static MyPopupWindow window;
	private static AscertainPopupWindow windoww;
	private Date currentDate = new Date();
	public boolean isNetConnected;
	public SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private SpeechRecognizer mIat;
	private ImageView iv_catt_soundBtn;
	private Handler addDataHandler = new ServerHandler() {

		@Override
		public void onSuccess(Bundle data, String state, String msg) {
			if (state.equals("001")) {
				String dataStr = data.getString("data");
				Log.e("HTTP", "数据采集" + dataStr);
				Toast.makeText(MainDataPickFragment.this.getActivity(), "保存成功",
						0).show();
			} else {
				// 失败时调用缓存
			}
		}

		@Override
		public void onFail(Bundle data, String state) {

		}
	};

	private Handler addAllDataHandler = new ServerHandler() {

		@Override
		public void onSuccess(Bundle data, String state, String msg) {
			String dataStr = data.getString("data");
			Log.e("HTTP", "数据采集" + dataStr);
			if (state.equals("001")) {
				Toast.makeText(MainDataPickFragment.this.getActivity(), "保存成功",
						0).show();
			} else {

			}
		}

		@Override
		public void onFail(Bundle data, String state) {

		}
	};

	private Handler symptomHandler = new ServerHandler() {
		@Override
		public void onSuccess(Bundle data, String state, String msg) {
			if (state.equals("001")) {

				String dataStr = data.getString("data");
				Log.e("HTTP", "数据采集列表" + dataStr);
				otherData = HttpServer.gson.fromJson(dataStr,
						new TypeToken<List<Map<String, String>>>() {
						}.getType());

				otherAdapter = new TextAdapter(
						MainDataPickFragment.this.getActivity(), otherData);

				gv_catt_other.setAdapter(otherAdapter);
			} else {
				Toast.makeText(MainDataPickFragment.this.getActivity(), msg, 0)
						.show();
			}
		}

		@Override
		public void onFail(Bundle data, String state) {

		}
	};

	private Handler getAllDataHandler = new ServerHandler() {

		@Override
		public void onSuccess(Bundle data, String state, String msg) {
			if (state.equals(HttpCons.STATE_SUCCESS)) {
				String dataString = data.getString(HttpCons.DATA);
				Log.e("Http", dataString);

				Map<String, List<Map<String, String>>> dataAllList = HttpServer.gson
						.fromJson(
								dataString,
								new TypeToken<Map<String, List<Map<String, String>>>>() {
								}.getType());
				List<Map<String, String>> bloodCollection = dataAllList
						.get("BloodCollection");

				CommonUtil.listRemoveNull(bloodCollection);
				DecimalFormat df = new DecimalFormat("#.0");
				for (int i = 0; i < bloodCollection.size(); i++) {
					Map<String, String> eachMap = bloodCollection.get(i);
					String flag = eachMap.get("flag");
					if (eachMap.containsKey("bloodvalue")
							&& eachMap.get("bloodvalue") != null) {
						double avg = Double.parseDouble(eachMap
								.get("bloodvalue"));

						avg = Double.parseDouble(df.format(avg));
						if (avg > 0) {
							if (flag.equals("0")) {
								tv_catt_data_bloodSugar1.setText(avg + "");
								tv_catt_data_bloodSugar1
										.setBackgroundResource(sugar_data_bg);
								tv_catt_data_bloodSugar1
										.setTextColor(getResources().getColor(
												R.color.title_text));
							} else if (flag.equals("1")) {
								tv_catt_data_bloodSugar2.setText(avg + "");
								tv_catt_data_bloodSugar2
										.setBackgroundResource(sugar_data_bg);
								tv_catt_data_bloodSugar2
										.setTextColor(getResources().getColor(
												R.color.title_text));

							}
						}
					}
				}

				List<Map<String, String>> heartRate = dataAllList
						.get("heartRate");
				CommonUtil.listRemoveNull(heartRate);

				for (int i = 0; i < heartRate.size(); i++) {

					Map<String, String> eachMap = heartRate.get(i);
					if (eachMap.containsKey("heartrate")
							&& eachMap.get("heartrate") != null) {
						int avg = (int) Double.parseDouble(eachMap
								.get("heartrate"));
						if (avg > 0) {
							tv_catt_data_heartPlus.setText(avg + "");
							tv_catt_data_heartPlus
									.setBackgroundResource(plus_data_bg);
							tv_catt_data_heartPlus.setTextColor(getResources()
									.getColor(R.color.title_text));
						}
					}
				}
				List<Map<String, String>> collectionOfBloodPressure = dataAllList
						.get("CollectionOfBloodPressure");
				CommonUtil.listRemoveNull(collectionOfBloodPressure);
				for (int i = 0; i < collectionOfBloodPressure.size(); i++) {
					Map<String, String> eachMap = collectionOfBloodPressure
							.get(i);
					String flag = eachMap.get("flag");
					if (eachMap.containsKey("bloodpressure")
							&& eachMap.get("bloodpressure") != null) {
						int avg = (int) Double.parseDouble(eachMap
								.get("bloodpressure"));
						if (avg > 0) {
							if (flag.equals("0")) {
								tv_catt_data_pressture1.setText(avg + "");
								tv_catt_data_pressture1
										.setBackgroundResource(pressure_data_bg);
								tv_catt_data_pressture1
										.setTextColor(getResources().getColor(
												R.color.title_text));
							} else if (flag.equals("1")) {
								tv_catt_data_pressture2.setText(avg + "");
								tv_catt_data_pressture2
										.setBackgroundResource(pressure_data_bg);
								tv_catt_data_pressture2
										.setTextColor(getResources().getColor(
												R.color.title_text));
							}
						}
					}
				}

				List<Map<String, String>> OtherCondition = dataAllList
						.get("OtherCondition");
				if (OtherCondition != null) {
					CommonUtil.listRemoveNull(OtherCondition);
					for (int i = 0; i < OtherCondition.size(); i++) {
						Map<String, String> eachMap = OtherCondition.get(i);
						String diseaseid = eachMap.get("diseaseid");

						for (int j = 0; j < otherData.size(); j++) {
							if (otherData.get(j).containsKey("diseaseid")
									&& otherData.get(j).get("diseaseid")
											.equals(diseaseid)) {
								otherData.get(j).put("state", "1");
							} else {
								otherData.get(j).put("state", "0");
							}
						}
					}
					otherAdapter.notifyDataSetChanged();
				}

			} else {
				Toast.makeText(MainDataPickFragment.this.getActivity(), msg, 0)
						.show();
			}
		}

		@Override
		public void onFail(Bundle data, String state) {

		}
	};

	// 其他
	private Handler otherHandler = new ServerHandler() {

		@Override
		public void onSuccess(Bundle data, String state, String msg) {

			Log.e("data", otherData.toString());
			if (state.equals(HttpCons.STATE_SUCCESS)) {

				String dataStr = data.getString(HttpCons.DATA);
				Log.e("hhttp", "otherHandler" + dataStr);
				List<Map<String, String>> listMap = HttpServer.gson.fromJson(
						dataStr, new TypeToken<List<Map<String, String>>>() {
						}.getType());

				for (int j = 0; j < otherData.size(); j++) {
					for (int i = 0; i < listMap.size(); i++) {
						Map<String, String> eachMap = listMap.get(i);
						String diseaseid = eachMap.get("diseaseid");
						if (otherData.get(j).containsKey("diseaseid")
								&& otherData.get(j).get("diseaseid")
										.equals(diseaseid)) {

							otherData.get(j).put("state", "1");
							break;
						} else {
							otherData.get(j).put("state", "0");
						}
					}
				}
				Log.e("data", otherData.toString());
				otherAdapter.notifyDataSetChanged();

			} else {
				Toast.makeText(MainDataPickFragment.this.getActivity(), msg, 0)
						.show();
			}

		}

		@Override
		public void onFail(Bundle data, String state) {
			// TODO Auto-generated method stub
			super.onFail(data, state);
		}

	};

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {

		rootView = inflater.inflate(R.layout.fragment_main_pick, container,
				false);
		sDateformat = new SimpleDateFormat("yyyy-MM-dd");
		initView(rootView);
		return rootView;
	}

	private void initView(final View rootView) {

		mainView = rootView.findViewById(R.id.ll_pick_main);
		isPickSettingFound = false;

		if (selectedDate.isEmpty())
			selectedDate = DateFormatUtils.format(System.currentTimeMillis(),
					"yyyy-MM-dd");

		tv_main_pick_consultation = (TextView) rootView
				.findViewById(R.id.tv_main_pick_consultation);
		tv_main_pick_consultation.setOnClickListener(this);
		tv_catt_data_measure = (TextView) rootView
				.findViewById(R.id.tv_catt_data_measure);
		tv_catt_data_measure.setOnClickListener(this);
		tv_data_pick_pickdate = (TextView) rootView
				.findViewById(R.id.tv_data_pick_pickdate);
		tv_data_pick_pickdate.setOnClickListener(this);
		tv_catt_data_bloodSugar1 = (TextView) rootView
				.findViewById(R.id.tv_catt_data_bloodSugar1);
		tv_catt_data_bloodSugar1.setOnClickListener(this);
		tv_catt_data_bloodSugar2 = (TextView) rootView
				.findViewById(R.id.tv_catt_data_bloodSugar2);
		tv_catt_data_bloodSugar2.setOnClickListener(this);
		tv_catt_data_heartPlus = (TextView) rootView
				.findViewById(R.id.tv_catt_data_heartPlus);
		tv_catt_data_heartPlus.setOnClickListener(this);
		tv_catt_data_pressture1 = (TextView) rootView
				.findViewById(R.id.tv_catt_data_pressture1);
		tv_catt_data_pressture1.setOnClickListener(this);
		tv_catt_data_pressture2 = (TextView) rootView
				.findViewById(R.id.tv_catt_data_pressture2);
		tv_catt_data_pressture2.setOnClickListener(this);
		// 展示数据型 控件
		ll_catt_booldSugar_advise_pickTime = (RelativeLayout) rootView
				.findViewById(R.id.ll_catt_booldSugar_advise_pickTime);
		ll_catt_plus_advise_pickTime = (RelativeLayout) rootView
				.findViewById(R.id.ll_catt_plus_advise_pickTime);
		ll_catt_pressure_advise_pickTime = (RelativeLayout) rootView
				.findViewById(R.id.ll_catt_pressure_advise_pickTime);
		tv_catt_booldSugar_pickTime = (TextView) rootView
				.findViewById(R.id.tv_catt_booldSugar_pickTime);

		gv_catt_other = (MyGridView) rootView.findViewById(R.id.gv_catt_other);
		gv_catt_other.setOnItemClickListener(this);
		otherData = new ArrayList<Map<String, String>>();
		otherAdapter = new TextAdapter(getActivity(), otherData);
		gv_catt_other.setAdapter(otherAdapter);

		// 去掉点击时出现的默认边框
		gv_catt_other.setSelector(new ColorDrawable(Color.TRANSPARENT));

		initImage();
		refreshView();
		getOtherList();
		tv_data_pick_pickdate.setText(selectedDate);

	}

	private void initImage() {
		sugar_bg = R.drawable.selector_add_sugar_bg;
		pressure_bg = R.drawable.selector_add_pressure_bg;
		puls_bg = R.drawable.selector_add_plus_bg;
		plus_data_bg = R.drawable.plus_data_bg;
		pressure_data_bg = R.drawable.pressure_data_bg;
		sugar_data_bg = R.drawable.sugar_data_bg;
		alert_data_bg = R.drawable.alert_data_bg;
	}

	private View initDataInputDialog(LoginDialogListener dataListener, int i) {
		LayoutInflater inflater = LayoutInflater.from(this.getActivity());
		View view = inflater.inflate(R.layout.dialog_input_daaa, null);
		TextView tv_catt_dialogLeft = (TextView) view
				.findViewById(R.id.tv_catt_dialogLeft);
		tv_catt_dialogLeft.setOnClickListener(dataListener);
		TextView tv_catt_dialogRight = (TextView) view
				.findViewById(R.id.tv_catt_dialogRight);
		tv_catt_dialogRight.setOnClickListener(dataListener);
		return view;

	}

	private AlertDialog loginAlertDialog;

	@Override
	public void onClick(View v) {
		View dialogView = null;
		String trim = null;
		if (MyConst.getACCOUNT().equals("")) {

			View loginDialogView = initDataInputDialog(
					new LoginDialogListener(), 0);

			if (null != loginDialogView) {
				loginAlertDialog = DialogUtil.showDialog(this.getActivity(),
						loginDialogView, true);
				loginAlertDialog.show();
			}
		} else {
			if (isTheSameDay(currentDate, new Date())
					|| v.getId() == R.id.tv_data_pick_pickdate) {
				switch (v.getId()) {

				case R.id.tv_data_pick_pickdate:// 选择日期

					window = new MyPopupWindow(getActivity(),
							new MyPickResultListener(),
							R.layout.item_pick_date_layout, currentDate, null);
					window.setBackgroundDrawable(new BitmapDrawable());
					window.showAtLocation(mainView, Gravity.BOTTOM
							| Gravity.CENTER_HORIZONTAL, 0, 0);
					break;
				case R.id.tv_catt_data_measure:// 测量

					windoww = new AscertainPopupWindow(getActivity(),
							new MyPickResultListener());
					windoww.setBackgroundDrawable(new BitmapDrawable());
					windoww.showAtLocation(mainView, Gravity.BOTTOM
							| Gravity.CENTER_HORIZONTAL, 0, 0);

					break;
				case R.id.tv_catt_data_bloodSugar1:// 添加饭前血

					trim = tv_catt_data_bloodSugar1.getText().toString().trim();
					dialogView = initDataInputDialog(ADDTYPE_SUGAR_BEFOREMEAL,
							R.layout.dialog_input_data,
							new DataDialogListener(), trim);

					break;
				case R.id.tv_catt_data_bloodSugar2:// 添加饭后血糖

					trim = tv_catt_data_bloodSugar2.getText().toString().trim();
					dialogView = initDataInputDialog(ADDTYPE_SUGAR_AFTERMEAL,
							R.layout.dialog_input_data,
							new DataDialogListener(), trim);

					break;
				case R.id.tv_catt_data_heartPlus:// 添加心率

					trim = tv_catt_data_heartPlus.getText().toString().trim();
					dialogView = initDataInputDialog(ADDTYPE_PLUS,
							R.layout.dialog_input_data,
							new DataDialogListener(), trim);

					break;
				case R.id.tv_catt_data_pressture1:// 添加高压

					trim = tv_catt_data_pressture1.getText().toString().trim();
					dialogView = initDataInputDialog(ADDTYPE_PRESSURE_HIGH,
							R.layout.dialog_input_data,
							new DataDialogListener(), trim);

					break;
				case R.id.tv_catt_data_pressture2:// 添加低压

					trim = tv_catt_data_pressture2.getText().toString().trim();
					dialogView = initDataInputDialog(ADDTYPE_PRESSURE_LOW,
							R.layout.dialog_input_data,
							new DataDialogListener(), trim);

					break;
				case R.id.tv_main_pick_consultation:

					saveAllDate();

					break;

				}
				if (null != dialogView)
					alertDialog = DialogUtil.showDialog(getActivity(),
							dialogView, true);
			} else {
				CommonUtil.showToast("时间太过久远,无法添加或修改", 0);
			}
		}

	}

	private void postOtherDate() {
		TransferParameter parameter = new TransferParameter();
		parameter.setUsername(MyConst.getACCOUNT());
		Map<String, Object> map = new HashMap<String, Object>();
		List<String> diseaseIdList = new ArrayList<String>();
		for (int i = 0; i < otherData.size(); i++) {
			if (otherData.get(i).containsKey("state")
					&& otherData.get(i).get("state").equals("1")) {
				diseaseIdList.add(otherData.get(i).get("diseaseid"));
			}
		}
		map.put("diseaseid", diseaseIdList);
		map.put("diseasetime",
				CommonUtil.getFormatDate("yyy-MM-dd", new Date()));
		parameter.setData(map);
		new HttpServer().post(HttpCons.INSERT_PATIENT_SYMPTOM, parameter,
				addDataHandler);
	}

	private boolean isLoaded = false;

	/** 得到其他疾病列表 */
	private void getOtherList() {

		if (CommonUtil.isNetConnected(this.getActivity())) {
			HashMap<String, Object> map = new HashMap<String, Object>();
			TransferParameter parameter = new TransferParameter();
			parameter.setUsername(MyConst.getACCOUNT());
			parameter.setData(map);
			new HttpServer().post(HttpCons.QUERY_PATIENT_SYMPTOM_LIST,
					parameter, symptomHandler);
			isLoaded = true;
		} else {
			// 网络为连接 时
		}

	}

	private ScaleAnimation myAnimation_Scale;

	public class LoginDialogListener implements OnClickListener {
		@Override
		public void onClick(View v) {

			switch (v.getId()) {
			case R.id.tv_catt_dialogLeft:// 取消
				loginAlertDialog.dismiss();
				break;
			case R.id.tv_catt_dialogRight:// 确定

				Intent personinfoIntent = new Intent(
						MainDataPickFragment.this.getActivity(),
						LoginActivity.class);
				MainDataPickFragment.this.getActivity().startActivity(
						personinfoIntent);

			}
		}
	}

	/**
	 * 数据录入对话框的控件监听类
	 */
	public class DataDialogListener implements OnClickListener {
		private int addType;

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.tv_catt_dialogLeft:// 取消
				alertDialog.dismiss();
				break;
			case R.id.tv_catt_dialogRight:// 确定
				String trim = et_catt_data.getText().toString().trim();

				int result = isDataValid(trim, addType);
				if (result > 0) {
					rememberUserInput(trim, addType);
				} else if (result == -1) {
					CommonUtil.showToast("您输入的值超出或低于合理范围，请重新输入", 0);
					break;
				} else if (result == -2) {
					CommonUtil.showToast("高压不能小于低压,请检查！", 1, getActivity());
					break;
				} else if (result == -3) {
					CommonUtil.showToast("低压不能大于高压,请检查！", 1, getActivity());
					break;
				}
				alertDialog.dismiss();
				break;
			case R.id.iv_catt_soundBtn://
				et_catt_data.setText(null);
				hideSoftkeyboard();
				// 3.开始听写
				mIat.startListening(mRecoListener);
				// 开始动画
				myAnimation_Scale = new ScaleAnimation(1.0f, 0.6f, 1.0f, 0.6f,
						Animation.RELATIVE_TO_SELF, 0.5f,
						Animation.RELATIVE_TO_SELF, 0.5f);
				// 设置时间持续时间为 700 毫秒
				myAnimation_Scale.setDuration(300);
				myAnimation_Scale.setRepeatCount(20);
				myAnimation_Scale.setRepeatMode(Animation.REVERSE);
				iv_catt_soundBtn.startAnimation(myAnimation_Scale);
				break;
			}
		}

		public void setAddType(int addType) {
			this.addType = addType;
		}
	};

	// 听写监听器
	private RecognizerListener mRecoListener = new RecognizerListener() {
		// 听写结果回调接口(返回Json格式结果，用户可参见附录)；
		// 一般情况下会通过onResults接口多次返回结果，完整的识别内容是多次结果的累加；
		// 关于解析Json的代码可参见MscDemo中JsonParser类；
		// isLast等于true时会话结束。
		StringBuilder sb = new StringBuilder();

		public void onResult(RecognizerResult results, boolean isLast) {
			String text = JsonParser.parseIatResult(results.getResultString());
			// et_catt_data.append(text);
			sb.append(text);
			// et_catt_data.setSelection(et_catt_data.length());
			if (isLast) {
				// CommonUtil.showToast("识别成功!", 0);
				iv_catt_soundBtn.clearAnimation();
				String trim = sb.toString();
				Log.e("TAG", trim);
				if (!CommonUtil.isNumeric(trim)) {
					try {
						int cn2Arab = NumberUtils.numberCN2Arab(trim);
						if (cn2Arab == 0)
							CommonUtil.showToast("不好意思，没听清……请再试试", 0);
						et_catt_data.setText(cn2Arab + "");
					} catch (Exception e) {
						e.printStackTrace();
					}
				} else {
					et_catt_data.setText(trim);
				}
				sb.delete(0, sb.length());
				et_catt_data.setSelection(et_catt_data.length());
			}

		}

		// 会话发生错误回调接口
		public void onError(SpeechError error) {
			error.getPlainDescription(true); // 获取错误码描述
		}

		// 开始录音
		public void onBeginOfSpeech() {
			CommonUtil.showToast("请对着手机说出测量结果……", 0);
		}

		// 音量值0~30
		public void onVolumeChanged(int volume) {
		}

		// 结束录音
		public void onEndOfSpeech() {
			// CommonUtil.showToast("结束录音!", 0);
			iv_catt_soundBtn.clearAnimation();
		}

		// 扩展用接口
		public void onEvent(int eventType, int arg1, int arg2, String msg) {
		}
	};

	public void hideSoftkeyboard() {
		try {
			IBinder iBinder = iv_catt_soundBtn.getWindowToken();
			((InputMethodManager) getActivity().getSystemService(
					Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(
					iBinder, InputMethodManager.HIDE_NOT_ALWAYS);
		} catch (NullPointerException e) {

		}
	}

	private Map<String, String> AllInputData = new HashMap<String, String>();

	/**
	 * 记录并显示用户的录入
	 * 
	 * @param trim
	 *            得到的用户输入
	 * @param addType
	 *            用户的输入类型（血糖、血压、心率）
	 */
	public void rememberUserInput(String trim, int addType) {
		switch (addType) {
		case ADDTYPE_PLUS:

			tv_catt_data_heartPlus.setText(trim);
			plus = Integer.parseInt(trim);
			if (plus > 100 || plus < 60) {// 心率大于100小于50
				showAlert(tv_catt_data_heartPlus);
			} else {
				tv_catt_data_heartPlus.setBackgroundResource(plus_data_bg);
				tv_catt_data_heartPlus.setTextColor(getResources().getColor(
						R.color.title_text));
			}
			setPickTimeAndAdivse(addType, trim, null);

			AllInputData.put(addType + "", trim);
			break;
		case ADDTYPE_PRESSURE_HIGH:

			tv_catt_data_pressture1.setText(trim);
			highPressure = Integer.parseInt(trim);
			if (highPressure > 140 || highPressure < 90) {// 高压大于140小于100
				showAlert(tv_catt_data_pressture1);
			} else {
				tv_catt_data_pressture1.setBackgroundResource(pressure_data_bg);
				tv_catt_data_pressture1.setTextColor(getResources().getColor(
						R.color.title_text));
			}
			if (!tv_catt_data_pressture2.getText().toString().trim().isEmpty()) {
				setPickTimeAndAdivse(addType, trim, tv_catt_data_pressture2
						.getText().toString().trim());
			}
			AllInputData.put(addType + "", trim);
			break;
		case ADDTYPE_PRESSURE_LOW:
			tv_catt_data_pressture2.setText(trim);
			lowPressure = Integer.parseInt(trim);
			if (lowPressure > 90 || lowPressure < 60) {// 低压大于90小于60
				showAlert(tv_catt_data_pressture2);
			} else {
				tv_catt_data_pressture2.setBackgroundResource(pressure_data_bg);
				tv_catt_data_pressture2.setTextColor(getResources().getColor(
						R.color.title_text));
			}
			if (!tv_catt_data_pressture1.getText().toString().trim().isEmpty()) {
				setPickTimeAndAdivse(addType, tv_catt_data_pressture1.getText()
						.toString().trim(), trim);
			}
			AllInputData.put(addType + "", trim);
			break;
		case ADDTYPE_SUGAR_AFTERMEAL:
			tv_catt_data_bloodSugar2.setText(trim);
			afterMealSugar = Float.parseFloat(trim);
			if (afterMealSugar < 3.9f || afterMealSugar > 9.4f) {// 餐后血糖
																	// 餐后2小时血糖值：≤3.9≤7.8毫摩/升。
				showAlert(tv_catt_data_bloodSugar2);
			} else {
				tv_catt_data_bloodSugar2.setBackgroundResource(sugar_data_bg);
				tv_catt_data_bloodSugar2.setTextColor(getResources().getColor(
						R.color.title_text));
			}
			if (!tv_catt_data_bloodSugar1.getText().toString().trim().isEmpty()) {
				setPickTimeAndAdivse(ADDTYPE_SUGAR, tv_catt_data_bloodSugar1
						.getText().toString().trim(), trim);
			} else {
				setPickTimeAndAdivse(addType, "1", trim);
			}
			AllInputData.put(addType + "", trim);
			break;
		case ADDTYPE_SUGAR_BEFOREMEAL:
			tv_catt_data_bloodSugar1.setText(trim);
			beforeMealSugar = Float.parseFloat(trim);
			if (beforeMealSugar < 3.9f || beforeMealSugar > 6.1f) {// 餐前血糖
																	// 空腹血糖正常值：3.9～6.1毫摩尔/升
				showAlert(tv_catt_data_bloodSugar1);
			} else {
				tv_catt_data_bloodSugar1.setBackgroundResource(sugar_data_bg);
				tv_catt_data_bloodSugar1.setTextColor(getResources().getColor(
						R.color.title_text));
			}
			if (!tv_catt_data_bloodSugar2.getText().toString().trim().isEmpty()) {
				setPickTimeAndAdivse(ADDTYPE_SUGAR, trim,
						tv_catt_data_bloodSugar2.getText().toString().trim());
			} else {
				setPickTimeAndAdivse(addType, trim, "0");
			}
			AllInputData.put(addType + "", trim);
			break;
		}
	}

	/** 保存所有的数据 */
	private void saveAllDate() {

		Set<String> eachType = AllInputData.keySet();
		HashMap<String, Object> map = new HashMap<String, Object>();
		TransferParameter parameter = new TransferParameter();
		List<Map<String, String>> pressureValueList = new ArrayList<Map<String, String>>();
		List<Map<String, String>> sugarValueList = new ArrayList<Map<String, String>>();

		parameter.setUsername(MyConst.getACCOUNT());
		for (String string : eachType) {
			int type = Integer.parseInt(string);
			switch (type) {
			case ADDTYPE_PLUS:
				map.put("heartrate", AllInputData.get(type + ""));
				break;
			case ADDTYPE_PRESSURE_HIGH:
				Map<String, String> bloodpressureMapHigh = new HashMap<String, String>();
				bloodpressureMapHigh.put("bloodpressure",
						AllInputData.get(type + ""));
				bloodpressureMapHigh.put("flag", "0");
				pressureValueList.add(bloodpressureMapHigh);
				break;
			case ADDTYPE_PRESSURE_LOW:
				Map<String, String> bloodpressureMapLow = new HashMap<String, String>();
				bloodpressureMapLow.put("bloodpressure",
						AllInputData.get(type + ""));
				bloodpressureMapLow.put("flag", "1");
				pressureValueList.add(bloodpressureMapLow);
				break;
			case ADDTYPE_SUGAR_AFTERMEAL:
				Map<String, String> sugarAftermeal = new HashMap<String, String>();
				sugarAftermeal.put("bloodvalue", AllInputData.get(type + ""));
				sugarAftermeal.put("flag", "1");
				sugarValueList.add(sugarAftermeal);
				break;
			case ADDTYPE_SUGAR_BEFOREMEAL:
				Map<String, String> sugarBeforemeal = new HashMap<String, String>();
				sugarBeforemeal.put("bloodvalue", AllInputData.get(type + ""));
				sugarBeforemeal.put("flag", "0");
				sugarValueList.add(sugarBeforemeal);
				break;

			}

		}
		if (pressureValueList.size() == 1) {
			if (pressureValueList.get(0).get("flag").equals("0")) {
				Toast.makeText(MainDataPickFragment.this.getActivity(),
						"请输入低压", 0).show();
			} else {
				Toast.makeText(MainDataPickFragment.this.getActivity(),
						"请输入高压", 0).show();
			}
		} else {

			List<String> diseaseIdList = new ArrayList<String>();
			for (int i = 0; i < otherData.size(); i++) {
				if (otherData.get(i).containsKey("state")
						&& otherData.get(i).get("state").equals("1")) {
					diseaseIdList.add(otherData.get(i).get("diseaseid"));
				}
			}
			map.put("bloodpressure", pressureValueList);
			map.put("bloodvalue", sugarValueList);
			map.put("diseaseid", diseaseIdList);
			map.put("measuretime",
					CommonUtil.getFormatDate("yyyy-MM-dd HH:mm:ss", new Date()));
			map.put("useraccount", MyConst.getACCOUNT());
			parameter.setData(map);
			Log.e("allData", HttpServer.gson.toJson(parameter));
			new HttpServer().post(
					HttpCons.ADD_SUGARBLOODPRESSUREHEARTRATEOFOTHER_DISEASES,
					parameter, addAllDataHandler);

		}
	}

	/**
	 * 用户单项指标出现异常时，把背景弄红，字体颜色弄红
	 * 
	 * @param tv_catt_data_bloodSugar22
	 */
	private void showAlert(TextView tv_catt_data_bloodSugar22) {
		tv_catt_data_bloodSugar22.setTextColor(getResources().getColor(
				R.color.emergency_text));
		tv_catt_data_bloodSugar22.setBackgroundResource(alert_data_bg);
	}

	/**
	 * 根据用户录入的数据添加评论并记录采集时间
	 * 
	 * @param addType
	 *            用户输入类型
	 * @param data2
	 * @param data1
	 */
	private void setPickTimeAndAdivse(int addType, String data1, String data2) {
		float float1;
		float float2;
		String adviseByData;
		ContentValues values = new ContentValues();

		String currentTime = DateFormatUtils.format(System.currentTimeMillis(),
				"HH:mm");
		switch (addType) {
		case ADDTYPE_PLUS:// 评价心率
			ll_catt_plus_advise_pickTime.setVisibility(View.VISIBLE);
			int pluss = Integer.parseInt(data1);
			tv_catt_plus_pickTime.setText(currentTime);
			adviseByData = CommonUtil.getAdviseByData(addType, pluss, 0);
			tv_catt_plus_advise.setText(adviseByData);
			comment_plus = adviseByData;
			// 存入数据库

			values.put("index_id", MyConst.PLUS);
			// values.put("index_value", pluss);
			// values.put("pick_time", currentTime);
			// plus_pickTime = currentTime;
			// values.put("pick_date", selectedDate);
			// plus_isNormal = CommonUtil.isNormal(addType, pluss);
			// values.put(MyConst.COLUMN_ISNORMAL, plus_isNormal);
			// values.put("last_modify_date", getDateTimeString());
			// saveData2DB(values);
			break;
		case ADDTYPE_PRESSURE_HIGH:
		case ADDTYPE_PRESSURE_LOW:// 评价血压
			int high = Integer.parseInt(data1);
			int low = Integer.parseInt(data2);
			// values.put("index_id", MyConst.PRESSURE_HIGH);
			// values.put("index_value", high);
			// pressure_pickTime = currentTime;
			// values.put("pick_time", currentTime);
			// values.put("pick_date", selectedDate);
			// pressure_high_isNormal =
			// CommonUtil.isNormal(ADDTYPE_PRESSURE_HIGH,
			// high);
			// values.put(MyConst.COLUMN_ISNORMAL, pressure_high_isNormal);
			// values.put("last_modify_date", getDateTimeString());
			// // 存入数据库
			// saveData2DB(values);
			values.clear();
			ll_catt_pressure_advise_pickTime.setVisibility(View.VISIBLE);

			// values.put("index_id", MyConst.PRESSURE_LOW);
			// values.put("index_value", low);
			// values.put("pick_time", currentTime);
			// values.put("pick_date", selectedDate);
			// pressure_low_isNormal = CommonUtil.isNormal(ADDTYPE_PRESSURE_LOW,
			// low);
			// values.put(MyConst.COLUMN_ISNORMAL, pressure_low_isNormal);
			// values.put("last_modify_date", getDateTimeString());
			tv_catt_pressure_pickTime.setText(currentTime);
			adviseByData = CommonUtil.getAdviseByData(addType, high, low);
			tv_catt_pressure_advise.setText(adviseByData);
			// comment_pressure = adviseByData;
			// // 存入数据库
			// saveData2DB(values);
			break;
		case ADDTYPE_SUGAR:
		case ADDTYPE_SUGAR_AFTERMEAL:
		case ADDTYPE_SUGAR_BEFOREMEAL:// 评价血糖
			ll_catt_booldSugar_advise_pickTime.setVisibility(View.VISIBLE);
			float1 = Float.parseFloat(data1);
			float2 = Float.parseFloat(data2);
			sugar_pickTime = currentTime;
			if (float1 > 0 && float2 > 0) {
				// values.put("pick_time", currentTime);
				// values.put("index_id", MyConst.SUGAR_BE);
				// values.put("index_value", float1);
				// values.put("pick_time", currentTime);
				// values.put("pick_date", selectedDate);
				// sugar_be_isNormal = CommonUtil.isNormal(
				// ADDTYPE_SUGAR_BEFOREMEAL, float1);
				// values.put(MyConst.COLUMN_ISNORMAL, sugar_be_isNormal);
				// values.put("last_modify_date", getDateTimeString());
				// saveData2DB(values);
				values.clear();

				// values.put("pick_time", currentTime);
				// values.put("index_id", MyConst.SUGAR_AF);
				// values.put("index_value", float2);
				// values.put("pick_time", currentTime);
				// values.put("pick_date", selectedDate);
				// sugar_af_isNormal = CommonUtil.isNormal(
				// ADDTYPE_SUGAR_AFTERMEAL, float2);
				// values.put(MyConst.COLUMN_ISNORMAL, sugar_af_isNormal);
				// values.put("last_modify_date", getDateTimeString());
				// saveData2DB(values);
				values.clear();
			} else if (float1 > 0) {
				// values.put("pick_time", currentTime);
				// values.put("index_id", MyConst.SUGAR_BE);
				// values.put("index_value", float1);
				// values.put("pick_time", currentTime);
				// values.put("pick_date", selectedDate);
				// sugar_be_isNormal = CommonUtil.isNormal(
				// ADDTYPE_SUGAR_BEFOREMEAL, float1);
				// values.put(MyConst.COLUMN_ISNORMAL, sugar_be_isNormal);
				// values.put("last_modify_date", getDateTimeString());
				// saveData2DB(values);
				values.clear();
			} else if (float2 > 0) {
				// values.put("pick_time", currentTime);
				// values.put("index_id", MyConst.SUGAR_AF);
				// values.put("index_value", float2);
				// values.put("pick_time", currentTime);
				// values.put("pick_date", selectedDate);
				// sugar_af_isNormal = CommonUtil.isNormal(
				// ADDTYPE_SUGAR_AFTERMEAL, float2);
				// values.put(MyConst.COLUMN_ISNORMAL, sugar_af_isNormal);
				// values.put("last_modify_date", getDateTimeString());
				// saveData2DB(values);
				values.clear();
			}
			tv_catt_booldSugar_pickTime.setText(currentTime);
			adviseByData = CommonUtil.getAdviseByData(addType, float1, float2);
			tv_catt_booldSugar_advise.setText(adviseByData);
			comment_sugar = adviseByData;
			break;
		}
	}

	// 刷新View
	private void refreshView() {

		if (sugar_pickTime != null) {
			if (!sugar_pickTime.isEmpty()) {
				ll_catt_booldSugar_advise_pickTime.setVisibility(View.VISIBLE);
				tv_catt_booldSugar_pickTime.setText(sugar_pickTime);
			}
		}
		tv_catt_booldSugar_advise = (TextView) rootView
				.findViewById(R.id.tv_catt_booldSugar_advise);
		if (afterMealSugar != 0) {
			tv_catt_data_bloodSugar2.setText(afterMealSugar + "");
			if (afterMealSugar < 3.9 || (afterMealSugar - 9.4) > 0.05) {// 餐后血糖
																		// 餐后2小时血糖值：≤3.9≤9.4毫摩/升。
				showAlert(tv_catt_data_bloodSugar2);
			} else {
				tv_catt_data_bloodSugar2.setBackgroundResource(sugar_data_bg);
				tv_catt_data_bloodSugar2.setTextColor(getResources().getColor(
						R.color.title_text));
			}
			ll_catt_booldSugar_advise_pickTime.setVisibility(View.VISIBLE);
			comment_sugar = CommonUtil.getAdviseByData(ADDTYPE_SUGAR_AFTERMEAL,
					0, afterMealSugar);
			tv_catt_booldSugar_advise.setText(comment_sugar);
		}
		if (beforeMealSugar != 0) {
			tv_catt_data_bloodSugar1.setText(beforeMealSugar + "");
			if (beforeMealSugar < 3.9 || beforeMealSugar > 6.1) {// 餐前血糖
																	// 空腹血糖正常值：3.9～6.1毫摩尔/升
				showAlert(tv_catt_data_bloodSugar1);
			} else {
				tv_catt_data_bloodSugar1.setBackgroundResource(sugar_data_bg);
				tv_catt_data_bloodSugar1.setTextColor(getResources().getColor(
						R.color.title_text));
			}
			ll_catt_booldSugar_advise_pickTime.setVisibility(View.VISIBLE);
			comment_sugar = CommonUtil.getAdviseByData(
					ADDTYPE_SUGAR_BEFOREMEAL, beforeMealSugar, 0);
			tv_catt_booldSugar_advise.setText(comment_sugar);
		}
		if (beforeMealSugar != 0 && afterMealSugar != 0) {
			ll_catt_booldSugar_advise_pickTime.setVisibility(View.VISIBLE);
			comment_sugar = CommonUtil.getAdviseByData(ADDTYPE_SUGAR,
					beforeMealSugar, afterMealSugar);
			tv_catt_booldSugar_advise.setText(comment_sugar);

		}

		tv_catt_pressure_pickTime = (TextView) rootView
				.findViewById(R.id.tv_catt_pressure_pickTime);
		if (pressure_pickTime != null) {
			if (!pressure_pickTime.isEmpty()) {
				ll_catt_pressure_advise_pickTime.setVisibility(View.VISIBLE);
				tv_catt_pressure_pickTime.setText(pressure_pickTime);
			}
		}
		tv_catt_pressure_advise = (TextView) rootView
				.findViewById(R.id.tv_catt_pressure_advise);

		if (highPressure != 0) {
			tv_catt_data_pressture1.setText(highPressure + "");
			if (highPressure > 140 || highPressure < 90) {// 高压大于140小于100
				showAlert(tv_catt_data_pressture1);
			} else {
				tv_catt_data_pressture1.setBackgroundResource(pressure_data_bg);
				tv_catt_data_pressture1.setTextColor(getResources().getColor(
						R.color.title_text));
			}
		}
		if (lowPressure != 0) {
			tv_catt_data_pressture2.setText(lowPressure + "");
			if (lowPressure > 90 || lowPressure < 60) {// 低压大于90小于60
				showAlert(tv_catt_data_pressture2);
			} else {
				tv_catt_data_pressture2.setBackgroundResource(pressure_data_bg);
				tv_catt_data_pressture2.setTextColor(getResources().getColor(
						R.color.title_text));
			}
		}
		if (highPressure != 0 && lowPressure != 0) {
			ll_catt_pressure_advise_pickTime.setVisibility(View.VISIBLE);
			comment_pressure = CommonUtil.getAdviseByData(ADDTYPE_PRESSURE_LOW,
					highPressure, lowPressure);
			tv_catt_pressure_advise.setText(comment_pressure);
		}

		tv_catt_plus_pickTime = (TextView) rootView
				.findViewById(R.id.tv_catt_plus_pickTime);
		if (plus_pickTime != null) {
			if (!plus_pickTime.isEmpty()) {
				ll_catt_plus_advise_pickTime.setVisibility(View.VISIBLE);
				tv_catt_plus_pickTime.setText(plus_pickTime);
			}
		}
		tv_catt_plus_advise = (TextView) rootView
				.findViewById(R.id.tv_catt_plus_advise);
		if (plus != 0) {
			tv_catt_data_heartPlus.setText(plus + "");
			if (plus > 100 || plus < 60) {// 心率大于100小于50
				showAlert(tv_catt_data_heartPlus);
			} else {
				tv_catt_data_heartPlus.setBackgroundResource(plus_data_bg);
				tv_catt_data_heartPlus.setTextColor(getResources().getColor(
						R.color.title_text));
			}
			comment_plus = CommonUtil.getAdviseByData(ADDTYPE_PLUS, plus, 0);
			ll_catt_plus_advise_pickTime.setVisibility(View.VISIBLE);
			tv_catt_plus_advise.setText(comment_plus);
		}

		// gv_catt_other.setAdapter(new TextAdapter(getActivity()));

		otherAdapter.notifyDataSetChanged();
	}

	/**
	 * 判断用户输入是否合法
	 * 
	 * @param trim
	 * @param addType
	 *            录入的指标类型
	 * @return
	 */
	public int isDataValid(String trim, int addType) {
		switch (addType) {
		case ADDTYPE_PLUS:// 心率：输入范围10-200，其它一律不合法，进行相关提示。
			try {
				if (trim.length() > 3 || trim.length() < 2) {
					return -1;
				} else if (Integer.parseInt(trim) <= 0
						|| Integer.parseInt(trim) > 200) {
					return -1;
				} else {
					return 1;
				}
			} catch (NumberFormatException e) {
				return -1;
			}
		case ADDTYPE_PRESSURE_HIGH:// 血压数值：输入范围是0-300 ，其它一律不合法，进行相关提示。
			try {
				if (trim.length() > 3 || trim.length() < 1) {
					return -1;
				} else if (Integer.parseInt(trim) <= 0
						|| Integer.parseInt(trim) > 300) {
					return -1;
				} else {
					if (!tv_catt_data_pressture2.getText().toString().trim()
							.isEmpty()) {
						String trimlow = tv_catt_data_pressture2.getText()
								.toString().trim();
						int intHigh = Integer.parseInt(trim);
						int intLow = Integer.parseInt(trimlow);
						if (intHigh < intLow) {
							return -2;
						}
					}
					return 1;
				}
			} catch (NumberFormatException e) {
				return -1;
			}

		case ADDTYPE_PRESSURE_LOW:
			try {
				if (trim.length() > 3 || trim.length() < 1) {
					return -1;
				} else if (Integer.parseInt(trim) <= 0
						|| Integer.parseInt(trim) > 300) {
					return -1;
				} else {
					if (!tv_catt_data_pressture1.getText().toString().trim()
							.isEmpty()) {
						String trimhigh = tv_catt_data_pressture1.getText()
								.toString().trim();
						int intlow = Integer.parseInt(trim);
						int inthigh = Integer.parseInt(trimhigh);
						if (inthigh < intlow) {
							return -3;
						}
					}
					return 1;
				}
			} catch (NumberFormatException e) {
				return -1;
			}
		case ADDTYPE_SUGAR_AFTERMEAL:// 输入范围0-30.0,整数部分2位以内，小数部分不超过1位—整体不超过3位，不合法则进行相关提示。
		case ADDTYPE_SUGAR_BEFOREMEAL:
			try {
				if (trim.startsWith(".")) {
					return -1;
				} else if (trim.length() > 4 || trim.length() < 1
						|| (Float.parseFloat(trim) < 10f && trim.length() > 3)) {
					return -1;
				} else if (Float.parseFloat(trim) <= 0
						|| Float.parseFloat(trim) > 30.0f) {
					return -1;
				} else {
					return 1;
				}
			} catch (NumberFormatException e) {
				return -1;
			}
		}
		return -1;
	}

	/***
	 * 初始化数据录入对话框
	 * 
	 * @param trim
	 * 
	 * @return
	 */
	private View initDataInputDialog(int addType, int layoutId,
			DataDialogListener dataListener, String trim) {
		if (trim == null)
			trim = "";
		LayoutInflater inflater = LayoutInflater.from(rootView.getContext());
		View view = inflater.inflate(layoutId, null);
		et_catt_data = (EditText) view.findViewById(R.id.et_catt_data);
		et_catt_data.setText(trim);
		et_catt_data.setSelection(et_catt_data.length());
		TextView tv_catt_noticeTile = (TextView) view
				.findViewById(R.id.tv_catt_noticeTile);
		TextView tv_catt_dataTile = (TextView) view
				.findViewById(R.id.tv_catt_dataTile);
		TextView tv_catt_datatips = (TextView) view
				.findViewById(R.id.tv_catt_datatips);
		iv_catt_soundBtn = (ImageView) view.findViewById(R.id.iv_catt_soundBtn);
		// 初始化语音输入按钮 如果有网，就初始化语音识别服务
		if (CommonUtil.isNetConnected(getActivity())) {
			//initSpeechRecognizer();
		} else {
			iv_catt_soundBtn.setVisibility(View.GONE);
		}
		iv_catt_soundBtn.setVisibility(View.GONE);
		dataListener.setAddType(addType);
		iv_catt_soundBtn.setOnClickListener(dataListener);
		view.findViewById(R.id.tv_catt_dialogLeft).setOnClickListener(
				dataListener);
		view.findViewById(R.id.tv_catt_dialogRight).setOnClickListener(
				dataListener);
		switch (addType) {
		case ADDTYPE_PLUS:
			tv_catt_noticeTile.setText("添加心率");
			tv_catt_dataTile.setText("心率：");
			et_catt_data.setInputType(InputType.TYPE_CLASS_NUMBER);
			tv_catt_datatips.setText("参考范围值：60~100次/分");
			break;
		case ADDTYPE_PRESSURE_HIGH:
			tv_catt_noticeTile.setText("添加血压");
			tv_catt_dataTile.setText("高压：");
			et_catt_data.setInputType(InputType.TYPE_CLASS_NUMBER);
			tv_catt_datatips.setText("参考范围值：90~140mmHg");
			break;
		case ADDTYPE_PRESSURE_LOW:
			tv_catt_noticeTile.setText("添加血压");
			tv_catt_dataTile.setText("低压：");
			et_catt_data.setInputType(InputType.TYPE_CLASS_NUMBER);
			tv_catt_datatips.setText("参考范围值：60~90mmHg");
			break;
		case ADDTYPE_SUGAR_AFTERMEAL:
			tv_catt_noticeTile.setText("添加血糖");
			tv_catt_dataTile.setText("餐后：");
			tv_catt_datatips.setText("参考范围值：3.9~9.4");
			break;
		case ADDTYPE_SUGAR_BEFOREMEAL:
			// tv_catt_noticeTile.setText("添加心率");
			// tv_catt_dataTile.setText("餐前：");
			break;

		}
		return view;
	}

	/**
	 * 初始化语音输入服务
	 */
	private void initSpeechRecognizer() {
		if (mIat == null) {
			String sound_app_id = CommonUtil.getMetaValue(getActivity(),
					"sound_app_id");

			SpeechUtility.createUtility(getActivity(), SpeechConstant.APPID
					+ "=" + sound_app_id);

			mIat = SpeechRecognizer.createRecognizer(getActivity(), null);
			// 2.设置听写参数，详见《科大讯飞MSC API手册(Android)》SpeechConstant类
			mIat.setParameter(SpeechConstant.DOMAIN, "iat");
			mIat.setParameter(SpeechConstant.LANGUAGE, "zh_cn");
			mIat.setParameter(SpeechConstant.ACCENT, "mandarin ");
			// 设置语音前端点
			mIat.setParameter(SpeechConstant.VAD_BOS, "5000");
			// 设置语音后端点
			mIat.setParameter(SpeechConstant.VAD_EOS, "1000");
			// 设置标点符号
			mIat.setParameter(SpeechConstant.ASR_PTT, "0");
			// 设置音频保存路径
			mIat.setParameter(SpeechConstant.ASR_AUDIO_PATH, Environment
					.getExternalStorageDirectory().getPath()
					+ "iflytek/wavaudio.pcm");
		}
	}

	@Override
	public boolean onTouch(View arg0, MotionEvent arg1) {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public String setPageName() {
		// TODO Auto-generated method stub
		return null;
	}

	private String desc;

	/**
	 * 获取控件选定结果的监听
	 * 
	 * @author wujiankun
	 */
	class MyPickResultListener implements GetPickResultListener {

		@Override
		public void onGetResult(Object[] results, int type) {
			switch (type) {
			case 0:
				if (results.length > 0) {

					selectedDate = (String) results[0];
					if (results.length == 2) {
						currentDate = (Date) results[1];
					}
					resetDataAndBackgroud();
					getHealthDataByDate();

				} else {
					CommonUtil.showToast("没有选上，再试一次吧", 0);
				}
				break;
			case 1:

				setData(results);

				break;

			case 2:
				desc = results[0].toString();
				tv_data_pick_pickdate.setText(desc);
				if (results.length == 2) {
					currentDate = (Date) results[1];
				}
				HashMap<String, Object> map = new HashMap<String, Object>();
				map.put("measure", desc);
				TransferParameter parameter = new TransferParameter();
				parameter.setUsername(MyConst.getACCOUNT());
				parameter.setData(map);
				new HttpServer().post(
						HttpCons.BLOOD_PRESSURE_DATA_QUERY_PATIENTSADAY,
						parameter, getAllDataHandler);
				initData();

			default:
				break;
			}

		}
	}

	public void setSugarData(String sugar, String data) {

		try {
			if (!isTheSameDay(currentDate, new Date())) {

				currentDate = new Date();
				tv_data_pick_pickdate.setText(DateFormatUtils.format(
						System.currentTimeMillis(), "yyyy-MM-dd"));
			}

			if (isBeforemealSugar(data)) {
				rememberUserInput(sugar, ADDTYPE_SUGAR_BEFOREMEAL);
			} else {
				rememberUserInput(sugar, ADDTYPE_SUGAR_AFTERMEAL);
			}
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/** 判断血糖的餐前餐后 */
	private boolean isBeforemealSugar(String data) throws ParseException {
		Date sugarData = sdf.parse(data);
		Calendar sugarCal = Calendar.getInstance();
		sugarCal.setTime(sugarData);
		int sugarhour = sugarCal.get(Calendar.HOUR_OF_DAY);
		int sugarminute = sugarCal.get(Calendar.MINUTE);

		if (((sugarhour * 60) + sugarminute) < (7 * 60)) {
			return true;
		} else {
			return false;
		}

	}

	public void setData(Object[] results) {

		if (results.length == 3) {
			rememberUserInput(results[2].toString(), ADDTYPE_PLUS);
			rememberUserInput(results[0].toString(), ADDTYPE_PRESSURE_HIGH);
			rememberUserInput(results[1].toString(), ADDTYPE_PRESSURE_LOW);

		} else {
			CommonUtil.showToast("测量失败", 0);
		}

	}

	/**
	 * 获取当前时间的年月日时分秒格式
	 * 
	 * @return 当前时间的年月日时分秒
	 */
	private String getDateTimeString() {
		return DateFormatUtils.format(System.currentTimeMillis(),
				"yyyy-MM-dd HH:mm:ss");
	}

	/**
	 * 初始化身体状态选择对话框（简单类型）
	 * 
	 * @param notice
	 * @param layoutId
	 * @param confirmListener
	 */
	private View initStatusSelectDialog(String notice, int layoutId,
			OnClickListener confirmListener) {
		LayoutInflater inflater = LayoutInflater.from(rootView.getContext());
		View view = inflater.inflate(layoutId, null);

		TextView noticeContent = (TextView) view
				.findViewById(R.id.tv_catt_NoticeContent);
		noticeContent.setText(notice);

		TextView leftBtn = (TextView) view
				.findViewById(R.id.tv_catt_dialogLeft);
		TextView rightBtn = (TextView) view
				.findViewById(R.id.tv_catt_dialogRight);

		rightBtn.setOnClickListener(confirmListener);
		leftBtn.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				alertDialog.dismiss();
			}
		});
		return view;
	}

	public static Fragment newInstance() {
		return new MainDataPickFragment();
	}

	/**
	 * 重置数据采集按钮背景
	 */
	private void resetDataAndBackgroud() {
		beforeMealSugar = 0;
		afterMealSugar = 0;
		highPressure = 0;
		lowPressure = 0;
		plus = 0;
		plus_pickTime = "";
		sugar_pickTime = "";
		pressure_pickTime = "";
		// bodyState = null;

		tv_catt_data_bloodSugar1.setText("");
		tv_catt_data_bloodSugar1.setBackgroundResource(sugar_bg);
		tv_catt_data_bloodSugar2.setText("");
		tv_catt_data_bloodSugar2.setBackgroundResource(sugar_bg);
		ll_catt_booldSugar_advise_pickTime.setVisibility(View.GONE);

		tv_catt_data_pressture1.setText("");
		tv_catt_data_pressture1.setBackgroundResource(pressure_bg);
		tv_catt_data_pressture2.setText("");
		tv_catt_data_pressture2.setBackgroundResource(pressure_bg);
		ll_catt_pressure_advise_pickTime.setVisibility(View.GONE);

		tv_catt_data_heartPlus.setText("");
		tv_catt_data_heartPlus.setBackgroundResource(puls_bg);
		ll_catt_plus_advise_pickTime.setVisibility(View.GONE);

		TextAdapter adapter = (TextAdapter) gv_catt_other.getAdapter();
		adapter.notifyDataSetChanged();
	}

	private AlertDialog progressDialog;

	private TextView tv_catt_data_measure;

	private List<Map<String, String>> otherData;
	private TextAdapter otherAdapter;
	private TextView tv_main_pick_consultation;
	private SimpleDateFormat sDateformat;

	private void getHealthDataByDate() {

		if (!checkNet()) {
			return;
		}
		// progressDialog = DialogUtil.startProgressDialog(getActivity(),
		// R.layout.dialog_progress, null);
		// 通过日期得到数据
	}

	/**
	 * 是否连网
	 * 
	 * @return
	 */
	private boolean checkNet() {
		isNetConnected = CommonUtil.isNetConnected(getActivity());
		if (!isNetConnected) {
			alertDialog = DialogUtil.showNetConnectionDialog(MyConst.activity,
					new OnCallBackListener() {
						@Override
						public void clickLeftButton() {
							alertDialog.dismiss();
							checkNet();
						}

						@Override
						public void clickRightButton() {
							alertDialog.dismiss();
						}
					});
		}
		return isNetConnected;
	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		String state = otherData.get(position).get("state");
		if (position == 0) {
			for (int i = 0; i < otherData.size(); i++) {
				if (i == 0) {
					otherData.get(i).put("state", "1");
				} else {
					otherData.get(i).put("state", "0");
				}
			}
		} else {
			otherData.get(0).put("state", "0");
			if (TextUtils.isEmpty(state) || state.equals("0")) {
				otherData.get(position).put("state", "1");
			} else {
				otherData.get(position).put("state", "0");
			}

		}
		otherAdapter.notifyDataSetChanged();
	}

	public void initData() {
		// 清空所有数据'
		resetDataAndBackgroud();
		// 初始化布局
		refreshView();
		// 清空其他病症
		for (int i = 0; i < otherData.size(); i++) {
			if (i == 0) {
				otherData.get(i).put("state", "1");
			} else {
				otherData.get(i).put("state", "0");
			}
		}
		otherAdapter.notifyDataSetChanged();

	}

	@Override
	public void setUserVisibleHint(boolean isVisibleToUser) {
		super.setUserVisibleHint(isVisibleToUser);
		if (isVisibleToUser) {
			// 相当于Fragment的onResume
			if (otherData != null && otherAdapter != null) {
				tv_data_pick_pickdate.setText(selectedDate);
				AllInputData.clear();
				initData();
				if (!TextUtils.isEmpty(MyConst.getACCOUNT())) {
					getOther();
				}
			}

		} else {
			// 相当于Fragment的onPause

		}
	}

	public void getOther() {

		TransferParameter parameter = new TransferParameter();
		parameter.setUsername(MyConst.getACCOUNT());
		parameter.setPagesize("50");
		parameter.setCurrentPage("1");
		HashMap<String, Object> data = new HashMap<String, Object>();
		data.put("beginTime",
				CommonUtil.getFormatDate("yyyy-MM-dd", new Date()));

		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DATE, 1);

		data.put("endTime",
				CommonUtil.getFormatDate("yyyy-MM-dd", cal.getTime()));
		parameter.setData(data);

		new HttpServer().post(HttpCons.QUERY_PATIENT_SYMPTOM, parameter,
				otherHandler);

	}

	public boolean isTheSameDay(Date d1, Date d2) {
		Calendar c1 = Calendar.getInstance();
		Calendar c2 = Calendar.getInstance();
		c1.setTime(d1);
		c2.setTime(d2);

		return (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR))
				&& (c1.get(Calendar.MONTH) == c2.get(Calendar.MONTH))
				&& (c1.get(Calendar.DAY_OF_MONTH) == c2
						.get(Calendar.DAY_OF_MONTH));
	}
}
